<?php


namespace App\Excel\Export;


use App\Http\Search\Order\ListIndexSearch;
use App\Models\Order;
use Illuminate\Database\Query\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\DefaultValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class OrderTrackingExport extends DefaultValueBinder implements FromQuery, WithHeadings, WithMapping, WithCustomValueBinder
{

    use Exportable;

    /**
     * @var ListIndexSearch
     * @author luffyzhao@vip.126.com
     */
    protected $search;

    /**
     * ProductExport constructor.
     * @param ListIndexSearch $search
     */
    public function __construct(ListIndexSearch $search)
    {
        $this->search = $search;
    }

    /**
     * @return Builder
     */
    public function query()
    {
        return Order::query()->where($this->search->toArray());
    }

    /**
     * @return array
     */
    public function headings(): array
    {
        return ['订单号','快递单号'];
    }

    /**
     * @param mixed $row
     *
     * @return array
     */
    public function map($row): array
    {
        return [
            $row->order_code,
            $row->tracking_number,
        ];
    }

    /**
     * @param Cell $cell
     * @param mixed $value
     * @return bool
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @author luffyzhao@vip.126.com
     */
    public function bindValue(Cell $cell, $value)
    {
        if(in_array($cell->getColumn(), ['A','B'])){
            $cell->setValueExplicit($value, DataType::TYPE_STRING);
            return true;
        }
        return parent::bindValue($cell, $value);
    }
}